import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      needLogin: false,
      needCoach: true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('@views/Cate'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  },
  {
    path: '/mime',
    name: 'mime',
    component: () => import('@views/Mime'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  },
  {
    path: '/list/:id',
    name: 'list',
    component: () => import('@views/List'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('@views/Order'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/contactList',
    name: 'contactList',
    component: () => import('@views/ContactList'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/contactAdd',
    name: 'contactAdd',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/contactEdit',
    name: 'contactEdit',
    component: () => import('@views/ContactEdit'),
    meta: {
      needLogin: true,
      needCoach: false
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  },
  {
    path: '/searchList',
    name: 'searchList',
    component: () => import('@views/SearchList'),
    meta: {
      needLogin: false,
      needCoach: false
    }
  }
]

const router = new VueRouter({
  routes
})
// 登陆
router.beforeEach((to, from, next) => {
  // 如果去的是登陆注册页面，不需要登陆
  if (to.fullPath === '/login' || to.fullPath === '/register') {
    next()
  } else {
    // 首先判断去的页面是否需要登陆，需要登陆，不需要就放行
    if (to.meta.needLogin) {
      // 说明需要登陆
      const token = localStorage.getItem('access_token')
      if (token) {
        next()
      } else {
        next({
          path: '/login',
          query: {
            from: to.fullPath
          }
        })
      }
    } else {
      next()
    }
  }
})

export default router
